import Toast from "../../../miniprogram_npm/@vant/weapp/toast/toast";
import Dialog from "../../../miniprogram_npm/@vant/weapp/dialog/dialog";
const QR = require('../../../utils/qrcode');
import {
  ajaxGetOrderDetails,
  ajaxWriteOffOrder,
  ajaxCancelOrderApplyRefund
} from '../../../api/order'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //自定义导航高度
    customNavHeight: app.globalData.customNavInfo.navHeight,
    baseURL: app.globalData.config.baseURL,
    //订单详情数据
    pageData: null,
    // 订单二维码
    qrcodeImg: null,
    isSlideShow: false,
    // 查询订单有误显示提示
    isShowErrorMsg: false,
    // 传入参数
    params: {
      // 核销确认
      isWriteOffConfirm: false,
      // 审核退款 | 待核销点击进入
      isRefundAudit: false
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    if (options.orderId) {
      //loading
      Toast.loading({
        message: '正在加载',
        forbidClick: true,
        duration: 0
      });
      try {
        let {
          data
        } = await ajaxGetOrderDetails({
          orderId: options.orderId
        });
        let pageData = Object.assign({}, (data || {}), {
          productInfoList: data.productInfoList || []
        })

        // 不是核销确认 && 未分配创建二维码
        if (!options.isWriteOffConfirm && pageData.orderStatus == 1) {
          // 页面初始化 options为页面跳转所带来的参数
          var size = this.setCanvasSize(); //动态设置画布大小
          this.createQrCode(pageData.orderId + '', "mycanvas", size.w, size.h);
        }

        this.setData({
          pageData,
          params: Object.assign({}, this.data.params, options || {})
        })
        await app.myNextTick()
        Toast.clear();
      } catch (err) {
        this.setData({
          isShowErrorMsg: true
        })
        await app.myNextTick()
        Toast.clear();
        Toast(err.msg || '查询订单错误');
      }
    }
  },
  //展开收起更多商品
  tabSlideShow() {
    this.setData({
      isSlideShow: !this.data.isSlideShow
    })
  },
  // 复制订单编号
  copy(e) {
    let {
      'text': str
    } = e.currentTarget.dataset;
    wx.setClipboardData({
      data: (str + '') || '',
      success(res) {
      }
    })
  },
  createQrCode: function (url, canvasId, cavW, cavH) {
    //调用插件中的draw方法，绘制二维码图片
    QR.api.draw(url, canvasId, cavW, cavH, this, this.canvasToTempImage);
  },
  //获取临时缓存图片路径，存入data中
  canvasToTempImage: function () {
    // 使用 setTimeout, 避免部分安卓机转出来的二维码图片不完整
    setTimeout(() => {
      wx.canvasToTempFilePath({
        canvasId: 'mycanvas',
        success: (res) => {
          let tempFilePath = res.tempFilePath;
          this.setData({
            qrcodeImg: tempFilePath,
          });
        },
        fail: (res) => {}
      });
    }, 100);
  },
  //适配不同屏幕大小的canvas
  setCanvasSize: function () {
    var size = {};
    try {
      var res = wx.getSystemInfoSync();
      var scale = 750 / 196; //不同屏幕下canvas的适配比例；设计稿是750宽
      var width = res.windowWidth / scale;
      var height = width; //canvas画布为正方形
      size.w = width;
      size.h = height;
    } catch (e) {
      // Do something when catch error
      // console.log("获取设备信息失败" + e);
    }
    return size;
  },
  // 核销订单
  async writeOffOrder() {
    try {
      // 已核销
      if (this.data.pageData.isUsed == 'Y') {
        return;
      }
      await Dialog.confirm({
        message: `确定核销吗?`,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonColor: "#e61211",
        zIndex: 120,
      })
    } catch (error) {
      return;
    }
    Toast.loading({
      message: '正在处理',
      forbidClick: true,
      duration: 0
    });
    try {
      await ajaxWriteOffOrder({
        id: this.data.pageData.orderId
      })
      await app.myNextTick()
      Toast.clear();
      //前往核销记录页面
      app.commonToPage(`/pages/order/writeOffRecord/index?showSuccess=${true}`, 'redirectTo')

    } catch (err) {
      await app.myNextTick()
      Toast.clear();
      Toast(err.msg || '错误');
    }
  },
  // 联系客服
  toContact() {
    app.commonNavigateTo('/pages/myInner/service/index')
  },
  // 退款
  toRefund() {
    let {
      orderStatus,
      orderId,
      totalPay
    } = this.data.pageData;
    // 未支付、已核销、退款成功
    if (orderStatus == 0 || orderStatus == 2 || orderStatus == 5) {
      return;
    }
    // 已申请退款
    if (orderStatus == 4) {
      Dialog.confirm({
          message: `确定取消该笔订单的退款申请吗？`,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          confirmButtonColor: "#e61211",
          zIndex: 120,
        })
        .then(async () => {
          try {
            Toast.loading({
              message: '正在处理',
              forbidClick: true,
              duration: 0
            });
            let {
              data
            } = await ajaxCancelOrderApplyRefund({
              orderId: orderId
            })
            // 重置订单状态
            this.setData({
              'pageData.orderStatus': data.orderStatus
            })
            await app.myNextTick()
            Toast.clear();
            // 生成二维码
            if (data.orderStatus == 1) {
              wx.nextTick(() => {
                // 页面初始化 options为页面跳转所带来的参数
                var size = this.setCanvasSize(); //动态设置画布大小
                this.createQrCode(orderId + '', "mycanvas", size.w, size.h);
              })
            }
          } catch (err) {
            await app.myNextTick()
            Toast.clear();
            Toast(err.msg || '取消失败');
          }
        })
        .catch(() => {});
    } else {
      // 未申请退款，前往申请退款页面
      app.commonNavigateTo('/pages/order/refundForm/index', {
        orderId,
        totalPay
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  }
})